package com.kanbox.api;

import java.io.UnsupportedEncodingException;

import org.json.JSONException;

import com.way.filemanager.FileManagerAppFrame;
import com.way.filemanager.fragment.PushSharePreference;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

public class Oauth extends Activity {
    protected WebView web;
    protected ProgressBar mProgressBar;

    private String client_id;
    private String client_secret;
    private String redirect_uri;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        LinearLayout linLayout = new LinearLayout(Oauth.this);
        LinearLayout.LayoutParams linearParam = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        LinearLayout.LayoutParams webViewParam = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        LinearLayout.LayoutParams progressParam = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 5);

        linLayout.setLayoutParams(linearParam);
        linLayout.setOrientation(LinearLayout.VERTICAL);

        web = new WebView(Oauth.this);
        web.setLayoutParams(webViewParam);

        mProgressBar = new ProgressBar(Oauth.this, null,
                android.R.attr.progressBarStyleHorizontal);
        mProgressBar.setMax(100);
        mProgressBar.setVisibility(View.GONE);
        mProgressBar.setLayoutParams(progressParam);

        linLayout.addView(mProgressBar);
        linLayout.addView(web);

        setContentView(linLayout);

        client_id = getIntent().getStringExtra("client_id");
        client_secret = getIntent().getStringExtra("client_secret");
        redirect_uri = getIntent().getStringExtra("redirect_uri");

        web.getSettings().setJavaScriptEnabled(true);
        web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        web.clearCache(true);
        web.clearCache(true);
        web.clearHistory();
        web.clearFormData();
        web.setWebViewClient(new EmbeddedWebViewClient());
        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int progress) {
                mProgressBar.setProgress(progress);
            }
        });
        web.loadUrl(getIntent().getStringExtra("url"));
    }

    private class EmbeddedWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        private void onProgressFinished() {
            mProgressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageFinished(WebView wv, String url) {
            onProgressFinished();
        }

        @Override
        public void onPageStarted(WebView wv, String url, Bitmap favicon) {
            mProgressBar.setVisibility(View.VISIBLE);
            handleUrl(url);
        }

        @Override
        public void onReceivedError(WebView wv, int errorCode,
                String description, String failingUrl) {
            onProgressFinished();
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                SslError error) {
            handler.proceed();
        }
    }

    @Override
    public void onResume() {
        //WebView.enablePlatformNotifications();
        super.onResume();
    }

    @Override
    public void onPause() {
        //WebView.disablePlatformNotifications();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (web.canGoBack()) {
                web.goBack();
            } else {
                web.stopLoading();
                // destoryThread();
                Oauth.this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean haveGetToken = false;

    private void handleUrl(String url) {
        if (haveGetToken)
            return;
        if (url != null && url.startsWith("https://www.kanbox.com")) {
            haveGetToken = true;
            String code = url.substring(url.indexOf("code=") + 5);

            try {
                Token.getInstance().getToken(client_id, client_secret, code,
                        redirect_uri, new MRequestListener());

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    private class MRequestListener implements RequestListener {
        @Override
        public void onComplete(String response, int operationType) {
            try {
                Token.getInstance().parseToken(response);
                saveToken(Token.getInstance());
                Oauth.this.finish();
                 Intent intent = new Intent(Oauth.this, FileManagerAppFrame.class);
                 intent.putExtra("isOnline", "true");
                 intent.putExtra("path", "/");
                 startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onError(KanboxException error, int operationType) {

        }
    }
     public void saveToken(Token token) {
            PushSharePreference sPreference = new PushSharePreference(Oauth.this, "oauth");
            sPreference.saveStringValueToSharePreferences("accecc_token", token.getAcceccToken());
            sPreference.saveStringValueToSharePreferences("refresh_token", token.getRefreshToken());
            sPreference.saveLongValueToSharePreferences("expries", token.getExpires());
        }

}
